package com.sun.androidexerciseproject.widget.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.AttributeSet;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.sun.androidexerciseproject.widget.util.LogUtil;

import java.net.URISyntaxException;

/**
 * Created by Administrator on 2016/5/20 0020.
 */
public class JftWebView extends WebView {
    private Context mContext;

    public JftWebView(Context context) {
        this(context, null);
    }

    public JftWebView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public JftWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        initSettings();
    }

    private class JftWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            if (url.startsWith("weixin://")) {
                wapPay(url);
            }
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            LogUtil.log("onPageStarted url = " + url + " webview url = " + view.getUrl());
        }

//        @Override
//        public void onPageFinished(WebView view, String url) {
//            LogUtil.log("onPageFinished url = " + url + " webview url = " + view.getUrl());
//            startActivity(url);
//            view.getSettings().setBlockNetworkImage(false);
//        }
    }

    private void startActivity(String url) {
        mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    }

    private void wapPay(String url) {
        Intent intent;
        try {
            intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
            intent.addCategory(Intent.CATEGORY_BROWSABLE);
            intent.setComponent(null);
            intent.setSelector(null);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } finally {
        }
    }

    private void initSettings() {
        WebSettings webSettings = getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDefaultTextEncodingName("utf-8");
        webSettings.setAllowFileAccess(true);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setBlockNetworkImage(true);
        webSettings.setAppCacheEnabled(true);
        setWebViewClient(new JftWebViewClient());
        requestFocus();
    }

}

